package com.knife.tools;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class ZipUtil {

	static final int BUFFER = 2048;

	public static void main(String[] args) throws IOException {
		try {
			ZipUtil t = new ZipUtil();
			t.zip("f:\\test.zip", "f:\\test");
			t.unzip("f:\\test.zip", "f:\\test2");
			t.deleteZip("f:\\test.zip");
		}

		catch (Exception e) {
			e.printStackTrace(System.out);
		}
	}

	public void deleteFile(File file) {
		if (file.exists()) {
			if (file.isFile()) {
				file.delete();
			} else if (file.isDirectory()) {
				File files[] = file.listFiles();
				for (int i = 0; i < files.length; i++) {
					this.deleteFile(files[i]);
				}
			}
			file.delete();
		} else {
			System.out.println("所删除的文件不存在！" + '\n');
		}
	}

	/**
	 * 删除文件
	 * 
	 * @date:2010-11-24
	 * @param zipFileName
	 *            要删除的文件名
	 */
	public void deleteZip(String zipFileName) {
		try {
			File zipFile = new File(zipFileName);
			if (zipFile.exists()) {// 查看文件是否存在
				System.out.println("文件" + zipFileName + "存在!");
				if (zipFile.delete()) {// 删除文件操作
					System.out.println("文件" + zipFileName + "刪除成功!");
				} else {
					System.out.println("文件" + zipFileName + "刪除失敗!");
				}
			} else {
				System.out.println("文件" + zipFileName + "不存在!");
			}
		} catch (Exception ex) {
			System.out.println("删除文件:" + ex.getMessage());
		}
	}

	/**
	 * 压缩文件
	 * 
	 * @date:2010-11-24
	 * @param zipFileName
	 *            压缩成的目的文件名
	 * @param inputFile
	 *            压缩的源文件名
	 * @throws Exception
	 */
	public void zip(String zipFileName, String inputFile) throws Exception {
		zip(zipFileName, new File(inputFile));
	}

	/**
	 * 压缩文件
	 * 
	 * @date:2010-11-24
	 * @param zipFileName
	 *            压缩成的目的文件名
	 * @param inputFile
	 *            压缩的源文件
	 * @throws Exception
	 */
	public void zip(String zipFileName, File inputFile) throws Exception {
		ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
				zipFileName));
		zip(out, inputFile, "");
		System.out.println("zip done");
		out.close();
	}

	/**
	 * 当unzip方法出现IllegalArgumentException异常时使用
	 * 
	 * @param zipfilepath
	 * @param unzippath
	 */
	public void ReadZip(String zipfilepath, String unzippath) {
		try {
			BufferedOutputStream bos = null;
			// 创建输入字节流
			FileInputStream fis = new FileInputStream(zipfilepath);
			// 根据输入字节流创建输入字符流
			BufferedInputStream bis = new BufferedInputStream(fis);
			// 根据字符流，创建ZIP文件输入流
			ZipInputStream zis = new ZipInputStream(bis);
			// zip文件条目，表示zip文件
			ZipEntry entry;
			// 循环读取文件条目，只要不为空，就进行处理
			while ((entry = zis.getNextEntry()) != null) {
				//System.out.println("====" + entry.getName());
				int count;
				byte date[] = new byte[BUFFER];
				// 如果条目是文件目录，则继续执行
				if (entry.isDirectory()) {
					continue;
				} else {
					int begin = zipfilepath.lastIndexOf(File.separator) + 1;
					int end = zipfilepath.lastIndexOf(".");
					String zipRealName = zipfilepath.substring(begin, end);
					bos = new BufferedOutputStream(new FileOutputStream(
							this.getRealFileName(
									unzippath + File.separator + zipRealName,
									entry.getName())));
					while ((count = zis.read(date)) != -1) {
						bos.write(date, 0, count);
					}
					bos.flush();
					bos.close();
				}
			}
			zis.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private File getRealFileName(String zippath, String absFileName) {
		String[] dirs = absFileName.split("/", absFileName.length());
		// 创建文件对象
		File file = new File(zippath);
		if (dirs.length > 1) {
			for (int i = 0; i < dirs.length - 1; i++) {
				// 根据file抽象路径和dir路径字符串创建一个新的file对象，路径为文件的上一个目录
				file = new File(file, dirs[i]);
			}
		}
		if (!file.exists()) {
			file.mkdirs();
		}
		file = new File(file, dirs[dirs.length - 1]);
		return file;
	}

	/**
	 * 解压文件
	 * 
	 * @date:2010-11-24
	 * @param zipFileName
	 *            压缩成的目的文件名
	 * @param outputDirectory
	 * @throws Exception
	 */
	public void unzip(String zipFileName, String outputDirectory)
			throws Exception {
		ZipInputStream in = new ZipInputStream(new FileInputStream(zipFileName));
		ZipEntry z;
		while ((z = in.getNextEntry()) != null) {
			System.out.println("unziping " + z.getName());
			if (z.isDirectory()) {
				String name = z.getName();
				name = name.substring(0, name.length() - 1);
				File f = new File(outputDirectory + File.separator + name);
				f.mkdir();
				System.out.println("mkdir " + outputDirectory + File.separator
						+ name);
			} else {
				File f = new File(outputDirectory + File.separator
						+ z.getName());
				f.createNewFile();
				FileOutputStream out = new FileOutputStream(f);
				int b;
				while ((b = in.read()) != -1)
					out.write(b);
				out.close();
			}
		}
		in.close();
	}

	/**
	 * 压缩文件
	 * 
	 * @date:2010-11-24
	 * @param out
	 * @param f
	 * @param base
	 * @throws Exception
	 */
	public void zip(ZipOutputStream out, File f, String base) throws Exception {
		System.out.println("Zipping  " + f.getName());
		if (f.isDirectory()) {
			File[] fl = f.listFiles();
			out.putNextEntry(new ZipEntry(base + "/"));
			base = base.length() == 0 ? "" : base + "/";
			for (int i = 0; i < fl.length; i++) {
				zip(out, fl[i], base + fl[i].getName());
			}
		} else {
			out.putNextEntry(new ZipEntry(base));
			FileInputStream in = new FileInputStream(f);
			int b;
			while ((b = in.read()) != -1)
				out.write(b);
			in.close();
		}
	}

}
